package com.app.couponsharelife.ui.main.home.shopweb

import android.content.ActivityNotFoundException
import android.content.Intent
import android.graphics.Bitmap
import android.util.Log
import android.view.View
import com.alibaba.baichuan.android.trade.AlibcTrade
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback
import com.alibaba.baichuan.android.trade.model.AlibcShowParams
import com.alibaba.baichuan.android.trade.model.OpenType
import com.alibaba.baichuan.android.trade.page.AlibcPage
import com.alibaba.baichuan.trade.biz.AlibcConstants
import com.alibaba.baichuan.trade.biz.context.AlibcResultType
import com.alibaba.baichuan.trade.biz.context.AlibcTradeResult
import com.alibaba.baichuan.trade.biz.core.taoke.AlibcTaokeParams
import com.hwangjr.rxbus.RxBus
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.main.me.order.NewOrderActivity
import com.app.couponsharelife.utils.AppUtils
import com.tencent.smtt.sdk.*
import com.tencent.smtt.utils.TbsLog
import kotlinx.android.synthetic.main.activity_taobaoweb.*
import java.net.URISyntaxException
import java.util.HashMap

/**
 *Created by xct on 2019/4/3
 *Description:淘宝
 */
class TaoBaoWebActivity:BaseActivity() {
    private var url=""
    private var name=""
    private var source=""
    private var webSettings:WebSettings?=null
    private var alibcShowParams: AlibcShowParams? = null//页面打开方式，默认，H5，Native
    private var exParams: HashMap<String, String>? = null//yhhpass参数
    private var alibcTaokeParams: AlibcTaokeParams? = null//淘客参数，包括pid，unionid，subPid
    override val viewLayoutId: Int
        get() = R.layout.activity_taobaoweb
    override fun initViews() {
        AppUtils.initImmersionBar(this,true)
        source= intent!!.getStringExtra("source")?:"" //intent.putExtra("source", "ExperienceMenPay")
        taobaoWeb_ivBack.setOnClickListener {
            //finish()
            if ("ExperienceMenPay"==source){
                val intent = Intent(this@TaoBaoWebActivity, NewOrderActivity::class.java)
                intent.putExtra("source", "ExperienceMenPay")
                intent.putExtra("Index", "1")
                startActivity(intent)
                finish()
            }else {
                onBackPressed()
            }
        }
        taobaoWeb_ivFinish.setOnClickListener {
            if ("ExperienceMenPay"==source){
                val intent = Intent(this@TaoBaoWebActivity, NewOrderActivity::class.java)
                intent.putExtra("source", "ExperienceMenPay")
                intent.putExtra("Index", "1")
                startActivity(intent)
                finish()
            }else {
                onBackPressed()
            }
        }
        name=intent!!.getStringExtra("name")?:""
        taobaoWeb_tvToolBarTitle.text=name
        initWebView()
    }
    private fun initWebView() {
        url=intent!!.getStringExtra("url")?:""
        showProgressDialog("请稍候")
        taobaoWeb_mWebView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                if (newProgress == 100) {
                    dismissProgressDialog()
                    taobaoWeb_mWebView.visibility = View.VISIBLE
                }
                super.onProgressChanged(view, newProgress)
            }
        }
        taobaoWeb_mWebView.webViewClient = object : WebViewClient() {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                if (url != null && url.contains("https://detail")) {

                } else{

                }
                super.onPageStarted(view, url, favicon)
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                if (url != null && url.contains("https://detail")) {

                } else {

                }
                super.onPageFinished(view, url)
            }

            override fun shouldOverrideUrlLoading(p0: WebView?, url: String?): Boolean {
                if (url!=null&&url.isNotEmpty()){
                    if (url.startsWith("http") || url.startsWith("https") || url.startsWith("ftp")){
                        Log.e("eee","常规链接---->${url}")
                        //http://127.0.0.1:12345/error?code=fdWuTuXdwFgZHQ8smRnueUlB4290749&state=1212
                        //'https://sj.qq.com/myapp/detail.htm?apkName=com.app.couponsharelife';
                        if (url.startsWith("https://detail")||url.startsWith("https://uland")||url.startsWith("https://h5.m.taobao")){
                            goTaoBao(url)
                            return true
                        }else if(url.contains("sj.qq.com")){
                            if ("ExperienceMenPay"==source) {
                                val intent = Intent(this@TaoBaoWebActivity, NewOrderActivity::class.java)
                                intent.putExtra("source", "ExperienceMenPay")
                                intent.putExtra("Index", "1")
                                startActivity(intent)
                                finish()
                            }else{
                                RxBus.get().post("selfOrder_RefreshData", "wechatrepay")
                                finish()
                            }
                            return true
                        }else{
                            return super.shouldOverrideUrlLoading(p0, url)
                        }
                    }else{
                        if (url.startsWith("tbopen://")){
                            return true
                        }else{
                            //Log.e("eee","AppUri---->${url}")
                            var intent: Intent?=null
                            try {
                                intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME)
                            } catch (e: URISyntaxException) {
                                return false
                            }
                            intent.setComponent(null)
                            try {
                                startActivity(intent)
                            } catch (e: ActivityNotFoundException) {
                                return false
                            }
                            return true
                        }
                    }
                }else{
                    return super.shouldOverrideUrlLoading(p0, url)
                }
            }
        }
        setWebString(url)
    }
    private fun setWebString(mIntentUrl:String){
        webSettings=taobaoWeb_mWebView.settings
        webSettings!!.allowFileAccess = true
        webSettings!!.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        webSettings!!.setSupportZoom(true)
        webSettings!!.builtInZoomControls = true
        webSettings!!.useWideViewPort = true
        webSettings!!.setSupportMultipleWindows(false)
        // webSetting.setLoadWithOverviewMode(true);
        webSettings!!.setAppCacheEnabled(true)
        // webSetting.setDatabaseEnabled(true);
        webSettings!!.domStorageEnabled = true
        webSettings!!.setJavaScriptEnabled(true)
        webSettings!!.setGeolocationEnabled(true)
        webSettings!!.setAppCacheMaxSize(java.lang.Long.MAX_VALUE)
        webSettings!!.setAppCachePath(this.getDir("appcache", 0).path)
        webSettings!!.databasePath = this.getDir("databases", 0).path
        webSettings!!.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .path)
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSettings!!.pluginState = WebSettings.PluginState.ON_DEMAND
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // webSetting.setPreFectch(true);
        val time = System.currentTimeMillis()
        taobaoWeb_mWebView.loadUrl(mIntentUrl)
        TbsLog.d("time-cost", "cost time: " + (System.currentTimeMillis() - time))
        CookieSyncManager.createInstance(this)
        CookieSyncManager.getInstance().sync()
    }
    private fun goTaoBao(url:String) {
        showCountDownProgressDialog("请稍候", 3)
        alibcShowParams = AlibcShowParams(OpenType.Native, false)
        exParams = HashMap()
        exParams!![AlibcConstants.ISV_CODE] = "appisvcode"
        exParams!!["alibaba"] = "阿里巴巴"//自定义参数部分，可任意增删改
        // 若非淘客taokeParams设置为null即可
        val pid = Contacts.ALIMAMA_PID //+ AppUtils.getString(Contacts.ADZONE_ID, "")
        alibcTaokeParams = AlibcTaokeParams()
        alibcTaokeParams?.adzoneid = "65231850041"//AppUtils.getString(Contacts.ADZONE_ID, "")
        alibcTaokeParams?.pid = pid
        alibcTaokeParams?.subPid = pid
        alibcTaokeParams?.extraParams = HashMap()
        (alibcTaokeParams?.extraParams as HashMap<String, String>)["taokeAppkey"] = Contacts.APP_ID
        (alibcTaokeParams?.extraParams as HashMap<String, String>)["relationId"] = AppUtils.getString(Contacts.ADZONE_ID, "")
        if (url == "") {
            showToastMsg("该商品暂时不能购买")
            return
        }
        val rlid="&relationId=${AppUtils.getString(Contacts.ADZONE_ID, "")}"
        AlibcTrade.show(this, AlibcPage(url+rlid), alibcShowParams, alibcTaokeParams, exParams, object : AlibcTradeCallback {
            override fun onTradeSuccess(tradeResult: AlibcTradeResult) {
                //当addCartPage加购成功和其他page支付成功的时候会回调
                if (tradeResult.resultType == AlibcResultType.TYPECART) {
                    //加购成功
                    showToastMsg("加购成功")
                } else if (tradeResult.resultType == AlibcResultType.TYPEPAY) {
                    //支付成功
//                    Log.d("order", tradeResult.payResult.paySuccessOrders[0])
                }
            }

            override fun onFailure(errCode: Int, errMsg: String) {
                showToastMsg("电商SDK出错,错误码=$errCode / 错误消息=$errMsg")
            }
        })
    }
    override fun onBackPressed() {
        if ("ExperienceMenPay"==source){
            val intent = Intent(this@TaoBaoWebActivity, NewOrderActivity::class.java)
            intent.putExtra("source", "ExperienceMenPay")
            intent.putExtra("Index", "1")
            startActivity(intent)
            finish()
        }else {
            if (taobaoWeb_mWebView.canGoBack()) {
                taobaoWeb_mWebView.goBack()
            } else {
                finish()
            }
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }
}